package com.kecheng.servermonitor.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.List;

@Service
public class MailService {
    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    public void sendAlertMail(List<String> toList, String subject, String content,Integer count,String clientId) {
        for (String to : toList) {
            try {
                MimeMessage message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
                helper.setFrom(from);
                helper.setTo(to);
                helper.setSubject(subject);
                helper.setText(content, false);
                mailSender.send(message);
                System.out.println(clientId+"服务异常第"+count+"次发送告警邮件给：" + to);
            } catch (Exception e) {
                System.err.println("发送邮件失败：" + e.getMessage());
            }
        }
    }
}
